package cool.tianyou.blue.bird.common.advice;

import cn.hutool.core.util.StrUtil;
import cool.tianyou.blue.bird.common.exception.SecurityAssessException;
import cool.tianyou.blue.bird.common.model.po.LoginUser;
import cool.tianyou.blue.bird.common.tool.LocalCache;
import cool.tianyou.blue.bird.common.tool.UserHolder;
import cool.tianyou.blue.bird.common.util.Assert;
import cool.tianyou.blue.bird.config.AuthConfiguration;
import cool.tianyou.blue.bird.module.synchronize.service.DeviceService;
import java.util.Optional;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Liutianyou
 * @date 2021/7/31 11:30 上午
 */

@RequiredArgsConstructor
@Component
public class AuthInterceptor implements HandlerInterceptor {


  private final AuthConfiguration authConfiguration;
  private final DeviceService deviceService;
  private final LocalCache localCache;

  @Override
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
      Object handler) {
    UserHolder.setUser(getLoginUser(request.getHeader("Authorization")));
    return true;
  }

  private LoginUser getLoginUser(String token) {
    if (authConfiguration.isMock()) {
      return authConfiguration.getMockUser();
    }
    Assert.isAuth(StrUtil.isNotBlank(token), "用户未登录");
    Optional<LoginUser> loginUser = localCache.get(token);
    loginUser.orElseThrow(() -> new SecurityAssessException("用户未登录"));
    LoginUser user = loginUser.get();
    user.setDeviceList(deviceService.getDeviceByUserId(user.getUserId()));
    return user;

  }

  @Override
  public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
      ModelAndView modelAndView) {
    UserHolder.close();
  }


}
